Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

For Loop in Java

In Java, the "for" loop is an entry-controlled loop that enables users to run a block of statements repeatedly for a predetermined number of times. The test-condition specified inside the "for" loop determines the number of iterations.
One of the simplest Java loops to learn is the "for" loop. Initialization, test, and update expressions, which together make up its loop-control, are all gathered at the top of the loop, inside of circular brackets ().

Below point are for loop's control flow:

Switch statement

  • The initialization procedure is carried out initially and only once. This step concludes with a semi colon and allows you to declare and initialise any loop control variables
  • After initialization Statements,this is second condition where Boolean expression is executed each time to test the condition of the loop..
  • If it is true,
    • Statements inside the body of for loop start executing
    • Then, statement of the for loop is executed till second condition get over. Here variable value is set to increased or decreased to met desire condition. It is an optional condition.
  • The “for” loop terminates if the Boolean expression is false.



Syntax

 for  (initialization expression, Boolean-expression , increment/decrement) { 
 // statements of for loop 
  } 

Flow Chart

 // java program using for loop  
public class Student { 
	public static void main(String[] args) {  		  
        int i;
        for(i = 1; i <= 10; i++)
        {
             System.out.println("2 * "+ i +"="+(2*i));
        }                    
    }  
}


Output:

2 * 1=2 
2 * 2=4 
2 * 3=6 
2 * 4=8 
2 * 5=10 
2 * 6=12 
2 * 7=14 
2 * 8=16 
2 * 9=18 
2 * 10=20 

Rules for using for Loops in Java

Let's learn about enum from below point

  • Variable inside for loop condition must be same time
  • for(int a = 0, float b = 1; b < 4; b++)
    if you write like this you will get compile time error like this "Syntax error on token "float", delete this token".
  • Any variable that is declared inside a for loop cannot be accessed after the loop statement. Because this variable is declared within a block of statements, the body of the loop becomes its scope.
     // java program using for loop  
    public class Student { 
    	public static void main(String[] args) {  		  
    		    for(int i = 0; i < 10 ; i++)
    		    {
    		      System.out.println(i);
    		    }	    
    		    System.out.println( "Value of i is " +i );  //Accessing i outside for loop body gives an error                 
        }  
    }
    

    Output:

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    	i cannot be resolved to a variable 

    Now variable can be accesed outside for loop

     // java program using for loop  
    public class Student { 
    	public static void main(String[] args) { 
             int i;
    	    for( i = 0; i < 10 ; i++)
    	    {
    	      System.out.println(i);
    	    }	    
    	   System.out.println( "Value of i is " +i );  //now accessing i outside for loop body will not  gives error                 
        }  
    } 
    

    Output:

    0 
    1 
    2 
    3 
    4 
    5 
    6 
    7 
    8 
    9 
    Value of i is 10 
  • We can have multiple initializations in for loop. The commas should be used to separate these several expressions inside the for loop.

  • Like initializations we may have multiple increment or decrement inside for loop with commas seprated.
     // java program using for loop  to show multiple initializations 
    public class Student { 
    	public static void main(String[] args) {     
            int a = 1; 
            for (int b = 0, c = 2; a < 5 && b < 5; a++, b++) {
                System.out.println("Value of b: "+b);         
            }
            System.out.println("Value of a: "+a);
        }  
    }  
    

    Output:

    Value of b: 0 
    Value of b: 1 
    Value of b: 2 
    Value of b: 3 
    Value of a: 5 
  • Even if the variable has already been declared outside of the "for" loop, we can declare it again in the initialization block of the loop.
  •  //  Redeclaration of a variable 
    public class Student { 
    	public static void main(String[] args) {     
    	    int a=10, b=10;  
    	    for(a=1,b=0; a<5; a++,b++)
    	    {
    	      System.out.println("Value of a is: "+a);
    	      System.out.println("Value of b is: "+b);
    	    }
        }  
    }  
    

    Output:

    Value of a is: 1 
    Value of b IS : 0 
    Value of a is: 2 
    Value of b is: 1 
    Value of a is: 3 
    Value of b is: 2 
    Value of a is: 4 
    Value of b is: 3 
  • we can skip any of the 3 condition in for loop. Let's see with example.
  •  //  Redeclaration of a variable 
    public class Student { 
    	public static void main(String[] args) {     
    	    int i = 2, sum = 0 ;
    	    for( ; i <= 20 ; sum +=i, i=2+i )
    	    {
    	    	 System.out.println(i);
    	    }
           System.out.println("The sum of first 10 multiple of 2 is: " +sum) ;
        }  
    }  
    

    Output:

    2 
    4 
    6 
    8 
    10 
    12 
    14 
    16 
    18 
    20 
    The sum of first 10 multiple of 2 is: 110 
  • By removing the test-expression, we can also produce an infinite loop. Let's see with example.
  •  //  Redeclaration of a variable 
    public class Student { 
    	public static void main(String[] args) {     
            for( int x = 10 ;   ; x-- )
            {
            	System.out.println("This is an example of infinite for loop");
            }           
        }  
    } 
    

    Output:

    This is an example of infinite for loop 
  • we can have multiple statements inside for loop as well as null statement inside for loop.

Java for-each Loop:

  • When traversing or iterating an Array or a Collection in Java, an Enhanced for loop is helpful. Due to the fact that we do not need to utilise a subscript notation or increment the value, it is simpler to use, write, and comprehend than a straightforward "for" loop.
  • Instead of using the element's index, the for-each loop bases its work on the elements. The elements in the specified variable are returned one by one.

Syntax

 for  (data_type variable_name: array_name) {
 //statements 
  } 

 // Java Loop program using for-each loop  
public class Student { 
	public static void main(String[] args) {     
        int arr[ ] = {5, 10, 15, 20, 25};
        for(int numDisplay : arr)
	    {
	      System.out.println(numDisplay+" ");
	    }          
    }  
}  

Output:

5 
10 
15 
20 
25 

Labeled for Loop in Java:

  • The name of each Java "for" loop can be obtained using the Labeled for loop in Java. We add a label before the for loop to do this. If we have nested for loops, a labelled for loop is helpful so that we may break or continue from the specific for loop with the aid of the label.

Syntax

labelname: 
 for  (initialization expression, Boolean-expression , increment/decrement) {
          //statements 
 } 

 // Java Loop program using for-each loop  
public class LabeledForExample
{
        public static void main(String[] args)
        {  
          xyz:   //Using Label for outer and for loop
            for(int a = 1; a <= 3; a++)
            {
              abc:
                for(int b = 1; b <= 3; b++)
                {
                  if(a==2 && b==2)
                  {
                    break xyz;
                  }
                  System.out.println(a+" "+b);
                }
            }
         }
    }
    



Output:

1 1 
1 2 
1 3 
2 1 

java While loop Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.